package client.ui.view.panel.main;

import base.BaseValue;
import client.assets.Icons;
import client.connect.HttpConnect;
import client.control.Controller;
import client.control.ResponseEntity;
import client.entity.Good;
import client.ui.component.button.FlatButton;
import client.ui.component.card.Card;
import client.ui.component.edittext.TextEdit;
import client.ui.component.scroll.SmallMouseWheelListener;
import client.ui.theme.ThisFont;
import client.ui.util.MaterialColors;
import client.ui.view.GoodsPage;
import client.ui.view.base.PanelControl;
import com.alibaba.fastjson.JSONObject;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
  * @Description 商品展示面板
  * @author 孔明浩
  * @Date 2020/3/31
  */
public class GoodsPanel extends JPanel implements ActionListener,PanelControl{
    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
    private JPanel itemPanel;
    private JPanel searchPanel;
    private JPanel choosePagePanel;
    private String searchText = "";
    private List<Good> goodList = new ArrayList<>();
    private int nowPage = 1;
    private int allPage = 1;
    public GoodsPanel() {
        super();
        initial();
        PanelControl.panels.put("GoodsPanel",this);
    }

    //初始化页面
    protected void initial(){
        this.setLayout(new BorderLayout());
        this.setBackground(MaterialColors.TEAL_50);
        //初始化搜索栏，标题和搜索框
        searchPanel = new JPanel(new BorderLayout());
        TextEdit search = new TextEdit("搜索商品");
        search.setEndImage(Icons.search);

        searchPanel.setBorder(new EmptyBorder(12,24,12,24));
        JLabel titleLabel = new JLabel("商品");
        titleLabel.setBorder(new EmptyBorder(0,24,0,24));
        titleLabel.setFont(ThisFont.VERY_BIG_BOLD_FONT);
        searchPanel.setBackground(MaterialColors.GRAY_300);
        search.setBackground(MaterialColors.GRAY_300);
        //添加组件，顺序不可改变，只能在之后追加
        searchPanel.add(titleLabel, BorderLayout.WEST);
        searchPanel.add(search,BorderLayout.EAST);

        //添加监听,点击搜索后的事件
        search.getEndLabel().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                search.setEndImage(Icons.search);
                if (search.getText() == null || search.getText().length() == 0){
                    searchText = "";
                    updatePanel("searchPanel");
                } else if (!searchText.equals(search.getText())){
                    searchText = search.getText();
                    updatePanel("searchPanel");
                }
            }
            //鼠标进入退出时设置不同的尾部图标
            @Override
            public void mouseEntered(MouseEvent e) {
                search.setEndImage(Icons.search1);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                search.setEndImage(Icons.search);
            }
        });
        //回车输入后的事件
        search.getTextField().addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER){
                    if (search.getText() == null || search.getText().length() == 0){
                        searchText = "";
                        updatePanel("searchPanel");
                    } else if (!searchText.equals(search.getText())){
                        searchText = search.getText();
                        updatePanel("searchPanel");
                    }
                }
            }
        });

        //初始化内容商品滚动栏
        GridLayout gridLayout = new GridLayout(2,4);
        gridLayout.setHgap(15);
        gridLayout.setVgap(4);
        itemPanel = new JPanel(gridLayout);
        for (int i = 0; i < 8; i++){
            Card card = new Card(i,"","载入中...", Double.NaN);
            itemPanel.add(card);
        }
        //滚动面板嵌套
        JScrollPane scrollPane = new JScrollPane(itemPanel);
        JScrollBar vScrollBar = scrollPane.getVerticalScrollBar();
        //重写滚轮事件
        scrollPane.addMouseWheelListener(new SmallMouseWheelListener(50,vScrollBar));
        scrollPane.setBorder(null);
        scrollPane.setWheelScrollingEnabled(false);

        //选择页面面板
        choosePagePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        //初始化选择面板，增加按钮监听
        FlatButton firstPageButton = new FlatButton("首页",null);
        firstPageButton.addActionListener(this);
        firstPageButton.setActionCommand("firstPage");
        FlatButton formerPageButton = new FlatButton("上一页",null);
        formerPageButton.addActionListener(this);
        formerPageButton.setActionCommand("formerPage");
        JTextField nowPageField = new JTextField("" + nowPage,4);
        //选择当前页面
        nowPageField.setEditable(false);
        //双击设置为可编辑状态
        nowPageField.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2){
                    nowPageField.setEditable(true);
                }
            }
        });
        //失去焦点提交数据，并设置为不可编辑状态
        nowPageField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                nowPageField.setEditable(false);
                GoodsPanel.this.actionPerformed(new ActionEvent(nowPageField,ActionEvent.ACTION_PERFORMED,"updateData"));
            }
        });
        //监听回车键,执行与失去焦点相同的动作
        nowPageField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER){
                    nowPageField.setEditable(false);
                    GoodsPanel.this.actionPerformed(new ActionEvent(nowPageField,ActionEvent.ACTION_PERFORMED,"updateData"));
                }
            }
        });

        JLabel allPageLabel = new JLabel("/ " + allPage);
        FlatButton nextPageButton = new FlatButton("下一页",null);
        nextPageButton.addActionListener(this);
        nextPageButton.setActionCommand("nextPage");
        FlatButton endPageButton = new FlatButton("尾页",null);
        endPageButton.addActionListener(this);
        endPageButton.setActionCommand("endPage");
        //添加顺序不可改变
        choosePagePanel.add(firstPageButton);
        choosePagePanel.add(formerPageButton);
        choosePagePanel.add(nowPageField);
        choosePagePanel.add(allPageLabel);
        choosePagePanel.add(nextPageButton);
        choosePagePanel.add(endPageButton);

        for (Component c:choosePagePanel.getComponents()) {
            if (c instanceof FlatButton){
                ((FlatButton) c).setPressedColor(MaterialColors.BLUE_900);
                ((FlatButton) c).setHoverColor(MaterialColors.BLUE_600);
                ((FlatButton) c).setNormalColor(MaterialColors.BLUE_800);
            }
        }

        this.add(searchPanel, BorderLayout.NORTH);
        this.add(scrollPane, BorderLayout.CENTER);
        this.add(choosePagePanel, BorderLayout.SOUTH);

        //更新利用网络组件
        updatePanel("searchPanel");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        switch (e.getActionCommand()){
            case "firstPage":
                nowPage = 1;
                updatePanel("itemPanel");
                break;
            case "formerPage":
                if (nowPage > 1){
                    nowPage--;
                    updatePanel("itemPanel");
                }
                break;
            case "nextPage":
                if (nowPage < allPage){
                    nowPage++;
                    updatePanel("itemPanel");
                }
                break;
            case "endPage":
                nowPage = allPage;
                updatePanel("itemPanel");
                break;
        }
    }

    /**
     * @Description 设计网络数据的更新操作，内部创建线程操作
     * @param object String 类型面板名称，支持itemPanel,searchPanel
     * @author 孔明浩
     * @Date 2020/4/4
     */
    @Override
    public void updatePanel(Object object) {
        String panelName = "";
        if (object instanceof String){
            panelName = (String) object;
        }
        if ("itemPanel".equals(panelName)){
            //判断搜索内容是否为空,执行刷新操作
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    ResponseEntity responseEntity = Controller.GOOD_CONTROL.getGoodByKey(
                            searchText, nowPage, 8
                    );
                    //code为1出错没有找到商品，code为0找到了商品
                    if (responseEntity.getCode() == 1){
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                itemPanel.removeAll();
                                itemPanel.validate();
                                itemPanel.repaint();
                                JLabel error = new JLabel("没有查到任何商品哦",SwingConstants.CENTER);
                                JLabel hint = new JLabel("请尝试其他关键字检索",SwingConstants.CENTER);
                                error.setForeground(MaterialColors.COSMO_RED);
                                error.setFont(ThisFont.VERY_BIG_BOLD_FONT);
                                hint.setForeground(MaterialColors.COSMO_BLUE);
                                hint.setFont(ThisFont.LARGE_BOLD_FONT);
                                itemPanel.add(error);
                                itemPanel.add(hint);
                            }
                        });
                    } else if (responseEntity.getCode() == 0){
                        allPage = Integer.parseInt(responseEntity.getMessage());
                        goodList = JSONObject.parseArray(responseEntity.getData(),Good.class);
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                //选择面板中的可编辑面板
                                JTextField edit = (JTextField) choosePagePanel.getComponent(2);
                                //选择面板中的总页数
                                JLabel label = (JLabel) choosePagePanel.getComponent(3);
                                //更新面板
                                edit.setText(nowPage + "");
                                //没错/就是用来好看的
                                label.setText("/ " + allPage);
                                itemPanel.removeAll();
                                //装填卡片
                                for (Good g:goodList){
                                    List<String> urls = JSONObject.parseArray(g.getPic(), String.class);
                                    //防止出现null异常
                                    String url = "";
                                    if (urls.size() > 0){
                                        url = urls.get(0);
                                    }
                                    Card card = new Card(g.getGoodId(),url,g.getGoodName(),g.getPrice());
                                    card.addMouseListener(new MouseAdapter() {
                                        @Override
                                        public void mouseClicked(MouseEvent e) {
                                            if (e.getButton() == MouseEvent.BUTTON1){
                                                //开设商品展示界面
                                                JFrame page = new GoodsPage(g.getGoodName(),g);
                                                page.setVisible(true);
                                            }

                                        }
                                    });
                                    itemPanel.add(card);
                                }
                                itemPanel.validate();
                                //防止重影
                                itemPanel.repaint();
                            }
                        });
                    }
                }
            });
        } else if ("searchPanel".equals(panelName)) {
            //判断搜索是否为空，若为空变体设置为所有商品
            ((JLabel) searchPanel.getComponent(0)).setText(searchText.length() == 0 ? "所有商品" : searchText);
            //初始化到第一页,清空历史页数
            nowPage = 1;
            allPage = 1;
            updatePanel("itemPanel");
        }
    }
}
